package org.proxywars.engine.rts;

import java.util.ArrayList;
import java.util.List;

import org.proxywars.engine.rts.events.TimerEvent;

public class Framework {

	private static Framework instance;
	List<IEvent> globalEvents = new ArrayList<IEvent>();

	private Framework() {
	}

	/**
	 * The players
	 */
	private List<IParty> parties = new ArrayList<IParty>();

	public void process() {
		IEvent timer = new TimerEvent();
		for (IParty party : parties) {
			party.handleEvent(timer);
			party.transferCreatedUnits();

			handleGlobalEvents(party);
		}
	}

	public void addParty(IParty party) {
		parties.add(party);
	}

	synchronized private void handleGlobalEvents(IParty party) {
		for (IEvent event : globalEvents) {
			party.handleEvent(event);
		}
		globalEvents.clear();
	}

	synchronized public void sendGlobalEvent(IEvent event) {
		globalEvents.add(event);
	}

	public static Framework getInstance() {
		if (instance == null)
			instance = new Framework();
		return instance;
	}

	public void log(IEvent event) {
		System.out.println("Event: " + event.getClass().getName());
		for (String attributeName : event.getAttributes().keySet()) {
			IAttribute attribute = event.getAttribute(attributeName);
			System.out.println("\tAttribute: " + attribute.getID() + "="
					+ attribute.getValue().toString());
		}
	}
}
